<?php

namespace addons\Merchants\backend\controllers;

use common\helpers\BcHelper;
use Yii;
use common\enums\AccountTypeEnum;
use common\enums\TransferTypeEnum;
use common\enums\StatusEnum;
use common\models\base\SearchModel;
use common\traits\MerchantCurd;
use common\models\forms\MerchantCreditsLogForm;
use common\models\merchant\CommissionWithdraw;
use common\models\forms\CommissionWithdrawForm;

/**
 * Class CommissionWithdrawController
 * @package addons\Merchants\backend\controllers
 * @author YiiFrame <21931118@qq.com>
 */
class CommissionWithdrawController extends BaseController
{
    use MerchantCurd;

    /**
     * @var CommissionWithdraw
     */
    public $modelClass = CommissionWithdraw::class;

    /**
     * 首页
     *
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'partialMatchAttributes' => [], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC,
            ],
            'pageSize' => $this->pageSize,
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query
            ->andWhere(['>=', 'status', StatusEnum::DISABLED]);

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    /**
     * @param $id
     * @return mixed
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionRefuse($id)
    {
        $model = Yii::$app->services->merchantCommissionWithdraw->findById($id);
        if ($model->state != StatusEnum::DISABLED) {
            return $this->message('申请已经被处理', $this->redirect(['index']), 'error');
        }

        if ($model->load(Yii::$app->request->post())) {
            $model->state = StatusEnum::DELETE;
            $model->save();

            // 退还余额
            Yii::$app->services->merchantCreditsLog->incrMoney(new MerchantCreditsLogForm([
                'merchant' => Yii::$app->services->merchant->findById($model->merchant_id),
                'num' => BcHelper::add($model->cash, $model->service_charge_total),
                'credit_group' => 'closeWithdraw',
                'remark' => '提现被拒绝返回',
                'map_id' => $model->id,
            ]));

            return $this->message('拒绝申请成功', $this->redirect(['index']));
        }

        return $this->renderAjax($this->action->id, [
            'model' => $model,
        ]);
    }

    /**
     * @param $id
     * @return mixed
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionPass($id)
    {
        $model = Yii::$app->services->merchantCommissionWithdraw->findById($id);
        if ($model->state != StatusEnum::DISABLED) {
            return $this->message('申请已经被处理', $this->redirect(['index']), 'error');
        }
        $model->transfer_money = $model->cash;

        if ($model->load(Yii::$app->request->post())) {
            // 事务
            $transaction = Yii::$app->db->beginTransaction();
            try {
                switch ($model->transfer_type) {
                    // 转账到银行卡
                    case TransferTypeEnum::WECHAT :
                        $result = Yii::$app->services->commissionWithdraw->wechatToBankCard(new CommissionWithdrawForm([
                            'withdraw_no' => $model->withdraw_no,
                            'enc_bank_name' => $model->bank_name,
                            'enc_bank_no' => $model->account_number,
                            'enc_true_name' => $model->realname,
                            'cash' => $model->cash,
                            'memo' => $model->memo,
                        ]));

                        $model->transfer_account_no = $result['partner_trade_no'];
                        break;
                    // 转账到支付宝
                    case TransferTypeEnum::ALI :
                        Yii::$app->services->commissionWithdraw->alipayToAccount(new CommissionWithdrawForm([
                            'withdraw_no' => $model->withdraw_no,
                            'enc_bank_no' => $model->account_number,
                            'enc_true_name' => $model->realname,
                            'cash' => $model->cash,
                            'memo' => $model->memo,
                        ]));
                        break;
                }

                $model->state = StatusEnum::ENABLED;
                $model->save();

                $transaction->commit();

                return $this->message('通过成功', $this->redirect(['index']));
            } catch (\Exception $e) {
                $transaction->rollBack();

                return $this->message($e->getMessage(), $this->redirect(['index']), 'error');
            }
        }

        $transferType = TransferTypeEnum::getMap();
        switch ($model->account_type) {
            case AccountTypeEnum::UNION :
                unset($transferType[TransferTypeEnum::ALI], $transferType[TransferTypeEnum::BALANCE]);
                break;
            case AccountTypeEnum::ALI :
                unset($transferType[TransferTypeEnum::WECHAT], $transferType[TransferTypeEnum::BALANCE]);
                break;
        }

        return $this->renderAjax($this->action->id, [
            'model' => $model,
            'transferType' => $transferType,
        ]);
    }

    /**
     * @param $withdraw_no
     * @return mixed|string
     */
    public function actionQuery($withdraw_no)
    {
        try {
            $message = Yii::$app->services->commissionWithdraw->queryByWithdrawNo($withdraw_no);

            return $this->message($message, $this->redirect(Yii::$app->request->referrer));
        } catch (\Exception $e) {
            return $this->message($e->getMessage(), $this->redirect(Yii::$app->request->referrer), 'error');
        }
    }
}